#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import fileutils
import hashlib
import json

# 获取文件md5
def getmd5(filename):  
    if not os.path.isfile(filename):
        return ""
    file_txt = open(filename,'rb').read()  
    m2 = hashlib.md5()
    m2.update(file_txt)
    return str(m2.hexdigest())

# 生成md5文件
# dir 需要生成的源路径
# save 保存路径 "E:\\tmp\\test\\md5.json"
def genmd5(dir, save):
    jsonkv = {}
    def __walk__(file):
        md5str = getmd5(file)
        key = file.replace(dir, "")
        key = key.replace("\\", "/")
        print (key + " " + md5str)
        jsonkv[key] = md5str
    fileutils.walkfile(dir, __walk__)

    if len(jsonkv) == 0:
        return

    jsonstr = json.dumps(jsonkv)
    #print (jsonstr)

    d = os.path.dirname(save)
    if not os.path.isdir(d):
        os.makedirs(d)

    f = open(save, "w")
    f.write(jsonstr)
    f.close()

#################################################

if __name__ == '__main__':
    genmd5("E:\\tmp\\test", "E:\\tmp\\test3\\md5.json")
    print ('aaa')